﻿
#include "gateserial.h"

gateSerial::gateSerial(QObject *parent)
    : QObject{parent}
{

}

gateSerial::~gateSerial()
{
    delete g_byteBuffer;
    closeGateSerial();
    g_timerRead->deleteLater();
    g_timerWrite->deleteLater();
}

void gateSerial::gateOnTimerReadCmd()
{
    if (g_gateCom->bytesAvailable() <= 0) {
        return;
    }

    QThread::msleep(g_sleepTime);
    QByteArray data = g_gateCom->readAll();
    int dataLen = data.length();
    if (dataLen <= 0) {
        return;
    }
    //追加
    g_byteBuffer->reserve(g_byteBuffer->size()+data.length());
    g_byteBuffer->append(data);
    gateOnReplyCmdParse();
    qDebug()<<"serial data :"<<data.toHex();

}

void gateSerial::gateOnTimerSendCmd()
{
    if (g_gateCom == 0 ){
         qDebug()<<"g_gateCom is null ";
        return;
    }
    if( !g_gateCom->isOpen()){
        qDebug()<<"serial open failed ,can't send data ";
        return ;
    }else {
    }

    if(g_listSendCmd.size()>0){
        g_gateCom->write(g_listSendCmd[0]);
        g_listSendCmd.removeAt(0);
        qDebug()<<"control cmd ";
    }else {
        g_gateCom->write(g_listControlCmd[0]);
    }
}


//解析--数据
//位置：09 09 00 00 12 00 xx
//上升/下降：09 f2 00 00 12 00  xx
//停止：09 f1 00 00 00 00 xx
void gateSerial::gateOnReplyCmdParse()
{
    if(g_byteBuffer->size() <=0)
        return;
    // timerRead->stop();
    QByteArray tmpBuffer=*g_byteBuffer;

    while ( g_byteBuffer->size())
 {
        //目标id
            int index=tmpBuffer.indexOf(0x09);
            if (index < 0) {
                tmpBuffer.clear();
                g_byteBuffer->clear();
                return ;
            }
            if(index>0){
                tmpBuffer.remove(0,index);
            }
            if (tmpBuffer.size() < 7) {
                qDebug()<<" reply size is low ";
                return;
            }
            quint8 compareNum=(static_cast<quint8>(tmpBuffer[1]));
            if ( compareNum!= 0xf2 &&compareNum!= 0x09 &&compareNum!= 0xf1) {
                tmpBuffer.remove(0,1);
                continue;
            }
            if(compareNum==0xf1){
                qDebug()<<"device scram ";

            }else if(compareNum==0xf2) {
                qDebug()<<"apex or buttom";
            }else if(compareNum==0x09) {
                qDebug()<<"queryDeviceHeight";
            }else {
                qDebug()<<"error data";
            }
            tmpBuffer.remove(0,7);
            *g_byteBuffer=tmpBuffer;
            continue;
        }

}

void gateSerial::openGateSerial(const QString &name)
{
    if(g_gateCom==0||!g_bcomOk){
        g_gateCom = new QextSerialPort(name, QextSerialPort::Polling);
        g_bcomOk = g_gateCom->open(QIODevice::ReadWrite);
        if (g_bcomOk) {
            g_gateCom->flush();
            g_gateCom->setBaudRate(BAUD115200);
            g_gateCom->setDataBits(DATA_8);
            g_gateCom->setParity(PAR_NONE);
            g_gateCom->setStopBits(STOP_2);
            g_gateCom->setFlowControl(FLOW_OFF);
            g_gateCom->setTimeout(10);
            g_timerRead->start();
            g_timerWrite->start();
        }
    }
}

void gateSerial::openSerial()
{

}

void gateSerial::closeGateSerial()
{
    if(g_gateCom!=0||g_bcomOk){
    g_timerRead->stop();
    g_timerWrite->stop();
    g_gateCom->close();
    g_gateCom->deleteLater();
    g_gateCom=0;
    g_bcomOk = false;
    }
}

void gateSerial::queryDeviceHeight()
{
    sendCmdToList(0);
}

void gateSerial::toDeviceZenith()
{
     sendCmdToList(2);
}

void gateSerial::toDeviceBottom()
{
     sendCmdToList(1);
}

void gateSerial::toDevcieScram()
{
     sendCmdToList(3);
}



void gateSerial::initGateSerial()
{
    // 相关配置--init
    g_bcomOk=false;
    g_gateCom=0;
    g_sleepTime=15;
    g_byteBuffer= new QByteArray;
    //connect(this,&gateSerial::parseMsg,this,&serialplc::OnReplyCmdParse);

    //读取数据
    g_timerRead = new QTimer();
    g_timerRead->setInterval(100);
    connect(g_timerRead,&QTimer::timeout,this,&gateSerial::gateOnTimerReadCmd);

    //发送数据
    g_timerWrite = new QTimer();
    g_timerWrite->setInterval(300);
    connect(g_timerWrite, SIGNAL(timeout()), this, SLOT(gateOnTimerSendCmd()));

    //创建固定指令
    //0查询-
    quint8 data[]={0x02,0x09,0x00,0x00,0x00,0x00,0x0B};
    QByteArray readbuffer;
    int len=   sizeof(data) / sizeof(data[0]);
    for (int i=0;i<len;i++){
        readbuffer.append(data[i]);
    }
    g_listControlCmd<<readbuffer;
    readbuffer.clear();
    //1 最低
    quint8  data1[]={0x02, 0xF2, 0x00, 0x00, 0x00,0x00,0xE2};
    len=sizeof(data1) / sizeof(data1[0]);
    for (int i=0;i<len;i++){
        readbuffer.append(data1[i]);
    }
    g_listControlCmd<<readbuffer;
    readbuffer.clear();
    //2 最高
    quint8 data2[]={0x02, 0xF2 ,0x00 ,0x00 ,0x12,0x00 ,0x79 };
    len=sizeof(data2) / sizeof(data2[0]);
    for (int i=0;i<len;i++){
        readbuffer.append(data2[i]);
    }
    g_listControlCmd<<readbuffer;
    readbuffer.clear();
    //3停止
    quint8 data3[]={0x02, 0xF1 ,0x00 ,0x00 ,0x00 ,0x00 ,0xF3};
    len=sizeof(data3) / sizeof(data3[0]);
    for (int i=0;i<len;i++){
        readbuffer.append(data3[i]);
    }
    g_listControlCmd<<readbuffer;
    readbuffer.clear();
}

quint16 gateSerial::CRC16_check(const QByteArray &data,int len)
{
    quint16 crcNum;
    crcNum = 0xFFFF;
    for (int i = 0; i < len; i++)
    {
        crcNum ^= data[i];
        for (int j = 0; j < 8; j++)
        {
        quint16 tmp;
        tmp = (unsigned int)(crcNum & 0x0001);
        crcNum >>= 1;
        if (tmp == 1)
        {
                crcNum ^= 0xA001;
        }
        }
    }

    return crcNum;
}

void gateSerial::sendCmdToList(int num)
{
    if(!g_bcomOk||g_gateCom==0)
        return;
    QList<QByteArray>::const_iterator it;
    for (it = g_listSendCmd.constBegin(); it != g_listSendCmd.constEnd(); ++it) {
        if (*it == g_listSendCmd.at(num)) {
        return;
        }
    }
    g_listSendCmd.append(g_listControlCmd.at(num));
}

